/* -----------------
* brief
* 1. this is code gen by tools
 */

package middleware

import (
	"github.com/mjiulee/lego"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"
	. "saas_sys_base/modules/appmanager/service"
	"strings"
)

//type MiddlewareHandle func (next fasthttp.RequestHandler) fasthttp.RequestHandler


var _appmanagerService AppManagerService
var AppAuthMiddleware lego.MiddlewareHandle = func (next fasthttp.RequestHandler) fasthttp.RequestHandler {
	return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
		ctxExt := &lego.RequestCtxExtent{ctx}
		if strings.HasPrefix(string(ctxExt.Path()), "/api/sys") {
			next(ctx)
			return
		}
		if string(ctxExt.Path()) == "/api/user/login"  ||
		string(ctxExt.Path()) == "/api/tenant/create_tenant_with_member"{
			next(ctx)
			return
		}
		sessionData := common.GetSessionData(ctxExt)
		//tokenWho := userData.TokenWho
		reqWho := sessionData.AppTokenWho
		hasPermission := false
		var err error
		for {

			// TODO 检测app是否开启上线

			//如果是来自终端用户的请求，则检测对应app(租户、app)是否过期
			//if tokenWho.IsUser() {
				hasPermission, err = _appmanagerService.CheckAppPermission(reqWho)
				if !hasPermission{
					break
				}

				hasPermission, err = _appmanagerService.CheckAppTenantPermission(reqWho)
				if !hasPermission{
					break
				}

			//} else if tokenWho.IsTenant() {

			//}


			//如果是来自租户的请求，则检测？？？
			//miniAppId := userData.TokenWho.GetMiniAppId()
			//attr := _appmanagerService.appAttrService.GetAppAttrByMiniAppId(_appmanagerService)
			//permission := _appmanagerService.appPermissionService.GetAppPermissionByMiniAppId(_appmanagerService)
			break
		}

		if !hasPermission {
			if err == nil {
				ctxExt.ResponseWithStateCode200(1, "APP权鉴失败")
				return
			}
			ctxExt.ResponseWithStateCode200(1, err.Error())
			return
		}

		next(ctx)
	})
}
